﻿using SelfManagement.Account.Manager;
using SelfManagement.Data.Constant;
using SelfManagement.Mvc;
using SelfManagement.Mvc.Result;
using SelfManagement.Utility.Extensions;
using SelfManagement.Web.Models.Session;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SelfManagement.Web.Infrastructure
{
    public class UserAuthorize : AuthorizeAttribute
    {
        public UserAuthorize()
        {

        }


        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            FormsAuthenticationHelper.RenewCurrentUser();
            if (!base.AuthorizeCore(httpContext))
            {
                return false;
            }
            else
            {
                var userSession = HttpContext.Current.Session[SessionConstant.USER_SESSION] as UserSession;
                var userManager = SelfManagement.IOC.Factory.StaticGetObject<UserManager>();
                var userId = httpContext.User?.Identity?.Name;

                //如果cookie还有效，但是session已经失效，重新初始化session
                if (userSession.IsNull())
                {
                    var user = userManager.Get(u => u.Id == userId);

                    if (user == null)//cookie有效，但是登录的可能是后台系统
                    {
                        return false;
                    }

                    userSession = new UserSession(user);
                    HttpContext.Current.Session[SessionConstant.USER_SESSION] = userSession;
                }

                return true;
            }
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult()
                {
                    Data = new JsonResultData() {
                        Messages = new List<string>() { "您无权进行此操作"}
                    }//ajax授权失败
                };
            }
            else
            {
                filterContext.Result = new RedirectToRouteResult(RouteConfig.Default,
                    SelfManagement.Mvc.Helper.RouteValuesHelper.From(
                        new
                        {
                            controller = "Account",
                            action = "Login",
                            returnUrl = filterContext.RequestContext.HttpContext.Request.RawUrl
                        })
                );
            }
        }
    }
}